import axios, { AxiosRequestConfig } from 'axios';
import { message } from 'antd';
import { API_BASE_URL } from '@/config';

const baseURL = process.env.REACT_APP_BASE_API || API_BASE_URL;

// 创建axios实例
const service = axios.create({
  baseURL,
  timeout: 30000, // 请求超时时间
});

// 是否正在刷新token
let isRefreshing = false;
// 等待刷新token的请求队列
let requests: Array<() => void> = [];

// 刷新token的函数
const refreshToken = async () => {
  try {
    const token = localStorage.getItem('token');
    if (!token) return null;

    // 发起刷新token请求
    const response = await axios({
      method: 'post',
      url: `${baseURL}/user/refresh-token`,
      headers: {
        Authorization: `Bearer ${token}`
      }
    });

    if (response.data && response.data.code === 200) {
      const { token: newToken } = response.data.data;
      // 存储新token
      localStorage.setItem('token', newToken);
      return newToken;
    }
    return null;
  } catch (error) {
    console.error('刷新Token失败:', error);
    return null;
  }
};

// 请求拦截器
service.interceptors.request.use(
  (config) => {
    // 从localStorage获取token
    const token = localStorage.getItem('token');
    if (token) {
      // 设置Authorization头
      config.headers.Authorization = `Bearer ${token}`;
    }
    return config;
  },
  (error) => {
    return Promise.reject(error);
  }
);

// 响应拦截器
service.interceptors.response.use(
  (response) => {
    const { data } = response;
    // 检查响应格式是否符合ResponseResult
    if (data && typeof data === 'object' && 'code' in data && 'message' in data) {
      if (data.code === 200) {
        return data.data;
      }
      message.error(data.message);
      return Promise.reject(new Error(data.message));
    }
    return data;
  },
  async (error) => {
    if (error.response) {
      const { status, config } = error.response;
      // 如果是401未授权错误（token过期或无效）
      if (status === 401) {
        if (!isRefreshing) {
          isRefreshing = true;
          const newToken = await refreshToken();
          isRefreshing = false;

          if (newToken) {
            // 执行队列中的请求
            requests.forEach(callback => callback());
            requests = [];

            // 使用新token重试当前请求
            config.headers.Authorization = `Bearer ${newToken}`;
            return service(config);
          }

          // 刷新token失败，清除本地存储的用户信息和token
          localStorage.removeItem('token');
          localStorage.removeItem('user');
          message.error('登录已过期，请重新登录');
          // 触发登录过期事件
          window.dispatchEvent(new Event('auth:expired'));
          return Promise.reject(error);
        }

        // 将请求加入队列
        return new Promise(resolve => {
          requests.push(() => {
            const token = localStorage.getItem('token');
            if (token) {
              config.headers.Authorization = `Bearer ${token}`;
              resolve(service(config));
            }
          });
        });
      }

      // 其他错误处理
      message.error(error.response.data?.message || '请求失败');
    } else {
      message.error('网络错误，请检查您的网络连接');
    }
    return Promise.reject(error);
  }
);

// 封装请求方法
const request = async <T = any>(config: AxiosRequestConfig): Promise<T | null> => {
  try {
    const response = await service(config);
    // response可能是null，所以返回类型是T | null
    return response as unknown as T;
  } catch (error) {
    return Promise.reject(error);
  }
};

export default request;
